package com.handa.documentManager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.handa.documentManager.entity.DO.OnlyofficeFileInfoDO;
import com.handa.documentManager.entity.VO.GenerateOfficeConfigParamVO;
import com.handa.documentManager.service.IOnlyofficeFileInfoService;
import com.handa.documentManager.service.OnlyOfficeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OnlyOfficeServiceImpl implements OnlyOfficeService {

    @Value("${onlyOffice.callback.url}")
    private String onlyOfficeCallbackUrl;


    @Resource
    private MinIOFileService minioFileService;

    @Resource
    private IOnlyofficeFileInfoService onlyofficeFileInfoService;

    @Override
    public String getDocType(String fileType) {
        String docType = "";
        List<String> fileTypesDoc = Arrays.asList(
                "doc", "docm", "docx", "dot", "dotm", "dotx", "epub", "fodt", "htm",
                "html", "mht", "odt", "ott", "pdf", "rtf", "txt", "djvu", "xps");
        List<String> fileTypesCsv = Arrays.asList(
                "csv", "fods", "ods", "ots", "xls", "xlsm", "xlsx", "xlt", "xltm", "xltx");

        List<String> fileTypesPPt = Arrays.asList(
                "fodp", "odp", "otp", "pot", "potm", "potx", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx");

        if (fileTypesDoc.contains(fileType)) {
            docType = "text";
        }
        if (fileTypesCsv.contains(fileType)) {
            docType = "spreadsheet";
        }
        if (fileTypesPPt.contains(fileType)) {
            docType = "presentation";
        }
        return docType;
    }

    @Override
    public String generateConfig(GenerateOfficeConfigParamVO paramVO) {
        log.info("onlyOffice 入参： " + JSONObject.toJSONString(paramVO));

        JSONObject config = new JSONObject();

        String fileType = getFileExtension(paramVO.getFileName());
        String fileName = paramVO.getFileName();
        String filePath = paramVO.getFilePath();
        String bucket = paramVO.getBucket();
        String fillFullPath = filePath + fileName;

        JSONObject permissions = new JSONObject();
        permissions.put("print", true);
        permissions.put("download", true);
        permissions.put("edit", true);


        JSONObject document = new JSONObject();
        document.put("fileType", fileType);

        String fileKey = getKey(fillFullPath);
        QueryWrapper<OnlyofficeFileInfoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bucket", bucket);
        queryWrapper.eq("absolute_path", fillFullPath);
        List<OnlyofficeFileInfoDO> list = onlyofficeFileInfoService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            fileKey = list.get(0).getFileKey();
        }

        document.put("key", fileKey);  // 唯一标识当前编辑会话
        document.put("title", fillFullPath);


        String minioFileUrl = minioFileService.getPresignedObjectUrl(bucket, fillFullPath);
        document.put("url", minioFileUrl);


        document.put("attachId", "key_" + convertChineseToUnicode(fileName));
        document.put("permissions", permissions);

        JSONObject close = new JSONObject();
        close.put("visible", true);
        close.put("text", "关闭文档");

        JSONObject customization = new JSONObject();
        customization.put("autosave", false);
        customization.put("compactToolbar", false);
        customization.put("forcesave", true);
        customization.put("toolbarNoTabs", false);
        customization.put("help", false);
        customization.put("compactHeader", true);
        customization.put("hideRightMenu", true);
        customization.put("close", close);


        JSONObject coEditing = new JSONObject();
        coEditing.put("mode", "fast");
        coEditing.put("change", false);

        JSONObject editorConfig = new JSONObject();
        editorConfig.put("callbackUrl", onlyOfficeCallbackUrl + fileName + "&bucket=" + bucket + "&path=" + filePath + "&userId=" + paramVO.getUserId());
        editorConfig.put("user", paramVO.getUser());
        editorConfig.put("mode", paramVO.getModel());
        editorConfig.put("lang", "zh-CN");
        editorConfig.put("customization", customization);
        editorConfig.put("coEditing", coEditing);


        config.put("documentType", getDocType(fileType));
        config.put("document", document);
        config.put("editorConfig", editorConfig);

        log.info("config: " + config);
        return config.toString();
    }

    @Override
    public String getKey(String fillFullPath) {

        String extraStr = "minio_";
        return "key_" + extraStr + convertChineseToUnicode(fillFullPath);
    }

    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public String convertChineseToUnicode(String chinese) {
        StringBuilder unicode = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String hexString = Integer.toHexString(c);
            // 确保每个Unicode编码是4位数
            if (hexString.length() <= 2) {
                hexString = "00" + hexString;
            }
            unicode.append(hexString.toUpperCase());
        }

        return unicode.toString();
    }
}
